package com.example.griddemo.adapter;

import android.content.Context;
import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.griddemo.R;
import com.example.griddemo.viewmodel.HotGoodsList;

import java.util.ArrayList;
import java.util.List;

public class HotGoodsAdapter extends RecyclerView.Adapter<HotGoodsAdapter.ViewHolder> {
    private final Context context;
    private List<HotGoodsList> dataList;

    public HotGoodsAdapter(Context context, List<HotGoodsList> dataList) {
        this.context = context;
        this.dataList = dataList != null ? dataList : new ArrayList<>();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context)
                .inflate(R.layout.item_hot_goods, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        HotGoodsList item = dataList.get(position);
        Glide.with(context).load(item.getPicUrl()).into(holder.ivImage);
        holder.tvName.setText(item.getName());
        holder.tvDesc.setText(item.getBrief());
        holder.tvPrice.setText(String.format("¥%.2f", item.getRetailPrice()));
        holder.tvOriginalPrice.setText(String.format("¥%.2f", item.getCounterPrice()));
        holder.tvOriginalPrice.setPaintFlags(holder.tvOriginalPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
    }

    public void updateData(List<HotGoodsList> newData) {
        this.dataList = newData != null ? newData : new ArrayList<>();
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView ivImage;
        TextView tvName;
        TextView tvDesc;
        TextView tvPrice;
        TextView tvOriginalPrice;

        ViewHolder(View itemView) {
            super(itemView);
            ivImage = itemView.findViewById(R.id.iv_hot_image);
            tvName = itemView.findViewById(R.id.tv_hot_name);
            tvDesc = itemView.findViewById(R.id.tv_hot_desc);
            tvPrice = itemView.findViewById(R.id.tv_hot_price);
            tvOriginalPrice = itemView.findViewById(R.id.tv_hot_original_price);
        }
    }
}